#include "Tree.hpp"

Tree::Tree():
    _root(NULL),
    _selection(NULL)
{
    _root = new Node();
    _root->setName("root");
    _root->redrawSubTree();
}

Tree::Tree(const Tree& orig)
{
    _root = new Node(*orig._root);
    _selection = NULL;
}

Tree::~Tree()
{
    delete _root;
}

void Tree::deleteSelectedNodes()
{
    bool shift = false;
    if(_selection && _selection->_father)
    {
        for(unsigned int i = 0; i < _selection->_father->_children.size(); i++)
        {
            if(_selection->_father->_children[i] == _selection)
            {
                if(i > 0)
                    _selection->_father->_children[i - 1]->_rightSibling =
                            _selection->_rightSibling;
                shift = true;
            }
            if(shift && (i < _selection->_father->_children.size() - 1))
                _selection->_father->_children[i] =
                        _selection->_father->_children[i + 1];
        }
         _selection->_father->_children.resize(_selection->_father->_children.size() - 1);
         delete _selection;
         _selection = NULL;
    }
}

Node* const Tree::getRoot() const
{
    return _root;
}

void Tree::redraw()
{
    if(_root)
        _root->redrawSubTree();
}


bool Tree::selectNode(int x, int y)
{
    _selection = NULL;
    selectNodeRec(_root, x, y, _root->getX(), _root->getY());
    return  _selection != NULL;
}

void Tree::selectNodeRec(Node* node, int x, int y, int xrep, int yrep)
{
    xrep = xrep+node->getX();
    yrep = yrep+node->getY();

    if (    xrep  < x &&
            xrep +  NODE_SIZE  > x &&
            yrep  < y &&
            yrep +  NODE_SIZE  > y) {
        _selection = node;
        return;
    }
    for(unsigned int i = 0 ; i < node->getChildren().size() ; i++){
        selectNodeRec(node->getChildren()[i], x, y, xrep, yrep);
        if (_selection != NULL)
            return;
    }
}

void Tree::moveSelectedNodesGraphically(int dx, int dy){
    if((_selection != NULL) && (_selection != _root))
        _selection->moveGraphically(dx,dy);
}

bool Tree::areSelectedNodesMovableGraphically(int dx, int dy){
    return true;
}


void Tree::toString(std::ostringstream& s){
    _root->toString(s);
}

void Tree::open(std::ifstream & i){
    _root->open(i);
}


